﻿using System.Threading.Tasks;
using System.Threading;
using Microsoft.Extensions.Hosting;
using System;
using Adp;
using Newtonsoft.Json.Linq;
using Yqd.Enm;
using Adp.Common;
using Yqd.Models;
using System.Linq;
using System.Collections.Generic;

namespace Yqd.Core
{
    public class UserHostService : BackgroundService
    {
        static string UnitCode = "";
        static string UnitName = "";
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                if (DateTime.Now.Hour == 0)
                {
                    Logs.Information<UserHostService>($"------开始更新人员-----");
                    using (var ctx = new YqdContext())
                    {
                        //var ctx = Fn.GetService<YqdContext>();
                        var ddService = Fn.GetService<DdService>();
                        var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
                        var users = ctx.Yqd_User.ToList();
                        List<string> listEmployee = new List<string>();
                        var departments = ctx.Yqd_Department.ToList();

                        JArray arr = new JArray();
                        int count = 0;
                        foreach (var d in departments)
                        {
                            var userList = ddService.pageOrganizationEmployeePositions(d.OrganizationCode, config.TenantId);
                            if (userList != null)
                            {
                                arr.Add(userList);
                                count += userList.Count;
                                //foreach (var o in userList)
                                //{
                                //    try
                                //    {
                                //        var it = JToken.Parse(o.ToString());
                                //        var oCode = it["govEmployeePositions"][0]["organizationCode"]?.ToString();
                                //        var unit = GetUnit(it["govEmployeePositions"][0]["empPosUnitCode"]?.ToString());
                                //        var employeeCode = it["employeeCode"].ToString();
                                //        var fullname = GetFullName(oCode);
                                //        var user = users.Where(x => x.EmployeeCode == it["employeeCode"]?.ToString()).FirstOrDefault();
                                //        if (user != null)
                                //        {
                                //            if (unit.UnitCode == user.UnitCode)
                                //            {
                                //                user.IsUpdateUnit = 0;
                                //            }
                                //            user.Name = it["employeeName"].ToString();
                                //            //user.Avatar = it["govEmpAvatar"]?.ToString() ?? "";
                                //            user.Gender = it["empGender"].ToString().ToInt();
                                //            user.OrganizationCode = oCode;
                                //            user.OrganizationName = fullname;
                                //            user.empJobLevelCode = it["empJobLevelCode"]?.ToString();
                                //            user.empBudgetedPostCode = it["empBudgetedPostCode"]?.ToString();
                                //            user.empJobLevelName = ddService.GetPropertyNameByCode("职级", it["empJobLevelCode"]?.ToString());
                                //            user.empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", it["empBudgetedPostCode"].ToString());
                                //            user.orderInOrganization = it["govEmployeePositions"][0]["orderInOrganization"]?.ToString();
                                //            user.gmtCreate = Convert.ToDateTime(it["gmtCreate"].ToString());
                                //            user.updateDate = DateTime.Now;
                                //            user.Status = it["govEmployeePositions"][0]["status"].ToString() == "F" ? 用户状态.已停用 : 用户状态.使用中;
                                //            ctx.SaveChanges();
                                //        }
                                //        else
                                //        {

                                //            ctx.Yqd_User.Add(new Yqd_User
                                //            {
                                //                AccountId = 0,
                                //                Openid = "",
                                //                Roles = "30",
                                //                PermitItem = "0",
                                //                EmployeeCode = employeeCode,
                                //                Name = it["employeeName"].ToString(),
                                //                //Avatar = it["govEmpAvatar"]?.ToString() ?? "",
                                //                Gender = it["empGender"].ToString().ToInt(),
                                //                OrganizationCode = oCode,
                                //                OrganizationName = fullname,
                                //                UnitCode = unit.UnitCode,
                                //                UnitName = unit.UnitName,
                                //                empJobLevelCode = it["empJobLevelCode"]?.ToString(),
                                //                empBudgetedPostCode = it["empBudgetedPostCode"].ToString(),
                                //                empJobLevelName = ddService.GetPropertyNameByCode("职级", it["empJobLevelCode"]?.ToString()),
                                //                empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", it["empBudgetedPostCode"].ToString()),
                                //                orderInOrganization = it["govEmployeePositions"][0]["orderInOrganization"]?.ToString(),
                                //                gmtCreate = Convert.ToDateTime(it["gmtCreate"].ToString()),
                                //                Status = it["govEmployeePositions"][0]["status"].ToString() == "F" ? 用户状态.已停用 : 用户状态.使用中,
                                //                Instime = DateTime.Now
                                //            });
                                //            var re = ctx.SaveChanges();
                                //        }
                                //        listEmployee.Add(it["employeeCode"]?.ToString());
                                //    }
                                //    catch (Exception ex)
                                //    {
                                //        Logs.Error<UserHostService>($"更新用户出错！{o.ToString()}，说明:{ex.Message}");
                                //        throw ex;
                                //    }
                                //}
                            }
                        }
                        var updateCount = 0;
                        foreach (var item in arr)
                        {
                            foreach (var o in item)
                            {

                                try
                                {
                                    var it = JToken.Parse(o.ToString());
                                    var employeeCode = it["employeeCode"]?.ToString();
                                    listEmployee.Add(employeeCode);
                                    var user = users.Where(x => x.EmployeeCode == employeeCode).FirstOrDefault();
                                    if (user != null)
                                    {
                                        if (user.updateDate != null)
                                        {
                                            var endDate = Convert.ToDateTime(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
                                            if (user.updateDate >= endDate)
                                            {
                                                continue;
                                            }
                                        }
                                    }
                                    var oCode = it["govEmployeePositions"][0]["organizationCode"]?.ToString();
                                    var unit = GetUnit(it["govEmployeePositions"][0]["empPosUnitCode"]?.ToString());
                                    var fullname = GetFullName(oCode);
                                    if (user != null)
                                    {
                                        if (unit.UnitCode == user.UnitCode)
                                        {
                                            user.IsUpdateUnit = 0;
                                        }
                                        //user.Name = it["employeeName"].ToString();
                                        ////user.Avatar = it["govEmpAvatar"]?.ToString() ?? "";
                                        //user.Gender = it["empGender"].ToString().ToInt();
                                        //user.OrganizationCode = oCode;
                                        //user.OrganizationName = fullname;
                                        //user.empJobLevelCode = it["empJobLevelCode"]?.ToString();
                                        //user.empBudgetedPostCode = it["empBudgetedPostCode"]?.ToString();
                                        //user.empJobLevelName = ddService.GetPropertyNameByCode("职级", it["empJobLevelCode"]?.ToString());
                                        //user.empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", it["empBudgetedPostCode"].ToString());
                                        //user.orderInOrganization = it["govEmployeePositions"][0]["orderInOrganization"]?.ToString();
                                        //user.gmtCreate = Convert.ToDateTime(it["gmtCreate"].ToString());
                                        //user.updateDate = DateTime.Now;
                                        //user.Status = it["govEmployeePositions"][0]["status"].ToString() == "F" ? 用户状态.已停用 : 用户状态.使用中;
                                        //ctx.SaveChanges();
                                    }
                                    else
                                    {
                                        var u = new Yqd_User
                                        {
                                            AccountId = 0,
                                            Openid = "",
                                            Roles = "30",
                                            PermitItem = "0",
                                            EmployeeCode = employeeCode,
                                            Name = it["employeeName"].ToString(),
                                            //Avatar = it["govEmpAvatar"]?.ToString() ?? "",
                                            Gender = it["empGender"].ToString().ToInt(),
                                            OrganizationCode = oCode,
                                            OrganizationName = fullname,
                                            UnitCode = unit.UnitCode,
                                            UnitName = unit.UnitName,
                                            empJobLevelCode = it["empJobLevelCode"]?.ToString(),
                                            empBudgetedPostCode = it["empBudgetedPostCode"].ToString(),
                                            empJobLevelName = ddService.GetPropertyNameByCode("职级", it["empJobLevelCode"]?.ToString()),
                                            empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", it["empBudgetedPostCode"].ToString()),
                                            orderInOrganization = it["govEmployeePositions"][0]["orderInOrganization"]?.ToString(),
                                            gmtCreate = Convert.ToDateTime(it["gmtCreate"].ToString()),
                                            Status = it["govEmployeePositions"][0]["status"].ToString() == "F" ? 用户状态.已停用 : 用户状态.使用中,
                                            updateDate = DateTime.Now,
                                            Instime = DateTime.Now
                                        };
                                        ctx.Yqd_User.Add(u);
                                        var re = ctx.SaveChanges();
                                        users.Add(u);
                                    }
                                    updateCount++;
                                }
                                catch (Exception ex)
                                {
                                    Logs.Error<UserHostService>($"更新用户出错！{o.ToString()}，说明:{ex.Message}");
                                    
                                }
                            }
                        }
                        var inUsers = users.Where(x => !listEmployee.Contains(x.EmployeeCode)).ToList();
                        foreach (var item in inUsers)
                        {
                            item.Status = 用户状态.已停用;
                            item.updateDate = DateTime.Now;
                            ctx.SaveChanges();
                        }
                        Logs.Information<UserHostService>($"更新总用户数 {count}条，更新成功{updateCount}条，停用的用户数{inUsers.Count}条");
                    }
                }
                Thread.Sleep(60000);
                await Task.Delay((1000 * 60 * 60), stoppingToken);
            }
        }

        private (string UnitCode, string UnitName) GetUnit(string OrganizationCode)
        {
            using (var ctx = new YqdContext())
            {
                //var ctx = Fn.GetService<YqdContext>();
                var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == OrganizationCode);
                if (org == null)
                {
                    return ("", "");
                }
                if (org.TypeCode == "GOV_UNIT")
                {
                    UnitCode = org.OrganizationCode;
                    UnitName = org.Name;
                }
                if (org.TypeCode == "GOV_HOLLOW_STRIP_NODE")
                {
                    return (UnitCode, UnitName);
                }
                return GetUnit(org.ParentCode);
            }
        }

        private List<string> GetChildIds(string parentOrganizationCode,List<string> ids)
        {
            using (var ctx = new YqdContext())
            {
                var org = ctx.Yqd_Department.Where(it => it.ParentCode == parentOrganizationCode).ToList();
                foreach(var item in org)
                {
                    ids.Add(item.OrganizationCode);
                    GetChildIds(item.OrganizationCode, ids);
                }
                return ids;
            }
        }
        private string GetFullName(string OrganizationCode)
        {
            using (var ctx = new YqdContext())
            {
                //var ctx = Fn.GetService<YqdContext>();
                List<string> list = new List<string>();
                var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == OrganizationCode);
                if (org == null)
                {
                    return "";
                }
                list.Add(org.Name);
                var result = GetParentName(list, org.ParentCode);
                result.Reverse();
                return string.Join(">", result);
            }
        }
        private List<string> GetParentName(List<string> str, string parentOrganizationCode)
        {
            using (var ctx = new YqdContext())
            {
                //var ctx = Fn.GetService<YqdContext>();
                var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == parentOrganizationCode);
                if (org == null)
                {
                    return str;
                }
                str.Add(org.Name);

                return GetParentName(str, org.ParentCode);
            }
        }
    }
}
